export default {
  // 为当前模块开启命名空间
    namespaced: true,
    state:() =>({
      // 购物车的数组，用来存储购物车中每个商品的信息对象
          // 每个商品的信息对象，都包含如下 6 个属性：
          // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
          cart: JSON.parse(uni.getStorageSync('cart') || '[]')
    }),
    // 模块的 mutations 方法
      mutations: {
        checkAll(state,flag){
          state.cart.forEach(g => g.goods_state = flag); 
          this.commit('m_cart/saveLocal');
        },
        removeGoods(state,goods){
          state.cart = state.cart.filter(g => g.goods_id != goods.goods_id);
          this.commit('m_cart/saveLocal');
        },
        updateCount(state,goods){
          let findRes = state.cart.find(g => g.goods_id === goods.goods_id);
          if(findRes){
            findRes.goods_count = goods.goods_count;
          }
          this.commit('m_cart/saveLocal');
        },
        updateGoods(state,goods){
          let findRes = state.cart.find(g => g.goods_id === goods.goods_id);
          if(findRes){
            findRes.goods_state = goods.goods_state;
          }
          this.commit('m_cart/saveLocal');
        },
        addCart(state,goods){
          const findRes = state.cart.find(g => g.goods_id === goods.goods_id);
          if(!findRes){
            state.cart.push(goods);
          } else{
            findRes.goods_count++;
          }
          this.commit('m_cart/saveLocal');
        },
        saveLocal(state){
          uni.setStorageSync('cart',JSON.stringify(state.cart));
        }
      },
      // 模块的 getters 属性
      getters: {
        total(state){
          return state.cart.reduce((total,item) => total += item.goods_count,0);
        },
        checkCount(state){
          return state.cart.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count ,0)
        },
        totalPrice(state){
          return state.cart.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2);
        }
      },
}